package cn.vinord.Controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.vinord.Enum.ResultEnum;
import cn.vinord.Properties.Properties;
import cn.vinord.Util.JavaBeanUtil;
import cn.vinord.Util.WeixinUtil;
import cn.vinord.Vo.AppLoginParams;
import cn.vinord.Vo.LoginResult;
import cn.vinord.Vo.PageResult;
import me.chanjar.weixin.common.exception.WxErrorException;

@RestController
public class OpenDoorController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private RestTemplate template;

	@Autowired
	private Properties properties;

	@Autowired
	private WxMaService wxMaService;
	

	@PostMapping("/app/loginSubmit")
	public LoginResult login(AppLoginParams params, HttpServletRequest request) {
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
		LoginResult result = new LoginResult();
		try {
			requestEntity = JavaBeanUtil.convertBeanToMap(params);
			String url = String.format("%s/app/loginSubmit", properties.getUrl().getUrl());
			result = template.postForEntity(url, requestEntity, LoginResult.class).getBody();
			logger.info("转调结果{}", result);
		} catch (Exception e) {
			logger.error("异常{}", e.getMessage());
		}
		return result;
	}

	@GetMapping("/app/code/{phone}")
	public PageResult fetchMsgCode(@PathVariable String phone) {
		PageResult result = new PageResult();
		try {
			String url = String.format("%s/app/code/%s", properties.getUrl().getUrl(), phone);
			result = template.getForObject(url, PageResult.class);
			logger.info("转调结果{}", result);
		} catch (RestClientException e) {
			result.setStatus(String.valueOf(ResultEnum.SERVER_ERROR.getValue()));
			logger.error("异常{}", result);
		}
		return result;
	}

	@GetMapping("/opendoor/apps")
	public PageResult doorRecords(long hostId, String dcode, final String formId, final String openId,
			final String name, final String cmutyName, HttpServletRequest httpServletRequest) throws WxErrorException {
		PageResult result = new PageResult();
		HttpEntity<String> request = setHeaders(httpServletRequest);
		String url = String.format("%s/opendoor/apps?hostId=%s&dcode=%s", properties.getUrl().getUrl(), hostId, dcode);
		result = requetNet(url, HttpMethod.GET, request, PageResult.class);
		logger.info("转调结果{}", result);
		if (result.getStatus().equals(ResultEnum.SUCCESS.getValue())) {
			sendTemplate(formId, openId, name, cmutyName);
		}
		if(result.getStatus().equals(ResultEnum.ERROR.getValue())){
			result.setStatus(ResultEnum.SERVER_ERROR.getValue());
		}
		return result;
	}

	@GetMapping("/opendoor/fetch")
	public PageResult fetchDoor(long cmutyId, long hostId, HttpServletRequest httpServletRequest) {
		PageResult result = new PageResult();
		HttpEntity<String> request = setHeaders(httpServletRequest);
		String url = String.format("%s/opendoor/fetch?cmutyId=%s&hostId=%s", properties.getUrl().getUrl(), cmutyId,hostId);
		result = requetNet(url, HttpMethod.GET, request, PageResult.class);
		if (result.getStatus().equals(ResultEnum.ERROR.getValue())) {
			result.setStatus(ResultEnum.SERVER_ERROR.getValue());
		}
		logger.info("转调结果{}", result);
		return result;
	}

	private <T> T requetNet(String url, HttpMethod method, HttpEntity<String> request, Class<T> t) {
		T result = null;
		try {
			result = t.newInstance();
			result = template.exchange(url, method, request, t, new LinkedMultiValueMap<>()).getBody();
			return result;
		} catch (Exception e) {
			logger.error("异常${}", e.getMessage());
			return result;
		}
	}

	private void sendTemplate(final String formId, final String openId, final String name, final String cmutyName) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (properties.getSystem().isSendTemplate() && !"the formId is a mock one".equals(formId)
						&& !StringUtils.isBlank(openId) && !"undefined".equals(formId)) {
					WeixinUtil weixinUtil = new WeixinUtil(wxMaService);
					weixinUtil.sendTemplate(formId, openId, name, cmutyName);
				}
			}
		}).start();
	}

	private HttpEntity<String> setHeaders(HttpServletRequest httpServletRequest) {
		HttpHeaders requestHeaders = new HttpHeaders();
		requestHeaders.add("USER-AGENT", "wechatdevtools");
		requestHeaders.add("token", httpServletRequest.getHeader("token"));
		HttpEntity<String> request = new HttpEntity<String>(null, requestHeaders);
		return request;
	}
}
